<template>
    <div style="margin: 10px;overflow: hidden">
        <Row>
            <Col span="6">
            <Card>
                <ButtonGroup>
                    <Button @click="toAddOrgVue()">增加</Button>
                    <Button @click="toRegOrgVue()">修改</Button>
                    <Button @click="deleteOrg()">删除</Button>
                </ButtonGroup>
                <Tree :data="orgTreeDate" @on-select-change="onSelectChange"></Tree>
            </Card>
            </Col>
            <Col span="17" offset="1">
                <Card>
                    <p slot="title">
                        查询 - {{orgParentName}}
                    </p>
                    <div class="search-con search-con-top">
                        <Select clearable v-model="searchKey" class="search-col" style="width: 100px;">
                            <Option v-for="item in columns" :value="item.key" :key="`search-col-${item.key}`">
                                {{ item.title }}
                            </Option>
                        </Select>
                        <Input clearable search placeholder="输入关键字搜索" class="search-input" v-model="searchValue" @on-search="handleSearch" />
                        <Button @click="handleSearch" class="search-btn" type="primary">
                            <Icon type="search"/>&nbsp;&nbsp;搜索
                        </Button>
                    </div>
                </Card>
                <Card style="margin-top: 10px;">
                    <ButtonGroup>
                        <Button @click="toAddUserButtonVue()">增加用户</Button>
                        <Button @click="toRegUserButtonVue()">修改用户</Button>
                        <Button @click="deleteUserButton()">删除用户</Button>
                    </ButtonGroup>
                    <Table ref="userTable" style="margin-top: 10px;" :data="userData"
                           :columns="userColumns" :highlight-row="true" :loading="loading"
                           @on-select="operationUserSelect" @on-select-cancel="operationUserSelect"
                           @on-select-all="operationUserSelect" @on-selection-change="operationUserSelect"
                           @on-sort-change="onSortChange" stripe>
                    </Table>
                    <Page style="margin-top: 5px;" show-elevator show-sizer show-total :total="total" :current="current"
                          :page-size="pageSize" @on-change="changePage" @on-page-size-change="changePageSize"></Page>
                </Card>
            </Col>
        </Row>
        <addOrg v-model="addShow" :orgParentId="orgParentId" :orgParentName="orgParentName" @reloadOrg="initOrgTree"></addOrg>
        <updateOrg v-model="updateShow" :orgId="orgParentId"  @reloadOrg="initOrgTree"></updateOrg>
        <addUser v-model="addUserShow" :orgParentId="orgParentId" :orgParentName="orgParentName" @handleSearch="handleSearch"></addUser>
        <updateUser v-model="updateUserShow" :userId="userId" @handleSearch="handleSearch"></updateUser>
    </div>
</template>
<script>

    import {getAllOrgList,deleteOrg} from '../../../api/sys/org/org-api';
    import {getUserList,deleteUser} from '../../../api/sys/user/user-api';
    import addOrg from './addOrg';
    import updateOrg from './updateOrg';
    import addUser from './addUser';
    import updateUser from './updateUser';

    export default {
        components: {
            addOrg,
            updateOrg,
            addUser,
            updateUser
        },
        data() {
            return {
                addUserShow:false,
                updateUserShow:false,
                userId:'',
                orgTreeDate:[],
                orgParentId:'0',
                orgParentName:'顶层节点',
                hasChildren: false,
                addShow:false,
                updateShow:false,
                columns: [{key: 'userName', title: '用户名字'}, {key: 'loginAccount', title: '用户账号'}],
                searchKey: '',
                searchValue: '',
                total: 0,
                current: 1,
                pageSize: 10,
                key:'crtDate',
                order:'desc',
                selection: [],
                loading:false,
                userData: [],
                userColumns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: '用户账号',
                        key: 'loginAccount',
                        sortable: true
                    },
                    {
                        title: '用户名字',
                        key: 'userName',
                        sortable: true
                    },
                    {
                        title: '用户邮箱',
                        key: 'email',
                        sortable: true
                    },
                    {
                        title: '所属组织',
                        key: 'orgName',
                        sortable: true
                    },{
                        title: '创建时间',
                        key: 'crtDate',
                        sortable: true,
                        render: (h, params) => {
                            let date = new Date(params.row.crtDate);
                            return h(
                                'div',
                                date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' +date.getSeconds()
                            );
                        }
                    }
                ]
            };
        },
        methods:{
            handleSearch(){
                this.loading = true;
                let searchKey = this.searchKey;
                let searchValue = this.searchValue;
                let orgParentId = this.orgParentId=='0'?'':this.orgParentId;
                let current = this.current;
                let pageSize = this.pageSize;
                let key = this.key;
                let order = this.order;
                let _this = this;
                getUserList({
                    current,
                    pageSize,
                    searchKey,
                    searchValue,
                    orgId:orgParentId,
                    sort:key,
                    order
                }).then(res => {
                    _this.total = res.totalCount;
                    _this.userData = res.result;
                    _this.loading = false;
                });
            },
            toAddUserButtonVue(){
                if (this.orgParentId == '0') {
                    this.$Message.warning('请先选择所属组织，再新增用户！');
                    return false;
                }
                this.addUserShow = true;
            },
            toRegUserButtonVue(){
                if(this.selection.length>1 || this.selection.length==0){
                    this.$Message.warning('请先选择一条需要修改的数据！');
                    return false;
                }
                this.updateUserShow  = true;
                this.userId = this.selection[0].userId;
            },
            deleteUserButton(){
                if(this.selection.length>1 || this.selection.length==0){
                    this.$Message.warning('请先选择一条需要删除的数据！');
                    return false;
                }
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>是否删除当前你选中的用户数据？</p>',
                    onOk: () => {
                        deleteUser({userId:this.selection[0].userId}).then(res=>{
                            if(res.result){
                                this.$Message.success('删除数据成功！');
                                // 删除数据成功同时刷新grid
                                this.handleSearch();
                            }else{
                                this.$Message.warning('删除数据失败！');
                            }
                        });
                    },
                    onCancel: () => {
                        this.$Message.info('您取消了当前的操作行为！');
                    }
                });
            },
            changePage(current) {
                this.current = current;
                this.handleSearch();
            },
            changePageSize(pageSize) {// 改变每页记录的条数
                this.pageSize = pageSize;
                this.handleSearch();
            },
            onSortChange(sort){
                if(sort.order=='normal'){
                    this.order = '';
                }else{
                    this.key = sort.key;
                    this.order = sort.order;
                }
                this.handleSearch();
            },
            operationUserSelect(selection) {
                this.selection = selection;
            },
            toAddOrgVue(){
                this.addShow = true;
            },
            toRegOrgVue(){
                if (this.orgParentId == '0') {
                    this.$Message.warning('请先选择一条需要修改的菜单节点！');
                    return false;
                }
                this.updateShow = true;
            },
            deleteOrg(){
                if (this.orgParentId == '0') {
                    this.$Message.warning('请先选择一条需要删除的菜单节点！');
                    return false;
                }
                if (this.hasChildren) {
                    this.$Message.warning('请先删除子菜单节点以后再来删除当前节点！');
                    return false;
                }
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>是否删除当前你选中的组织架构节点？</p>',
                    onOk: () => {
                        deleteOrg({orgId: this.orgParentId}).then(res => {
                            if (res.result) {
                                // 删除的时候也需要把选中的数据置空，否则新增的时候若是没选择具体的节点，他会默认该节点的数据
                                this.orgParentId = '0';
                                this.orgParentName = '顶层节点';
                                this.hasChildren = false;
                                this.$Message.success('删除组织架构数据成功！');
                                this.initOrgTree();
                            } else {
                                this.$Message.warning('删除组织架构数据失败！');
                            }
                        });
                    }
                });
            },
            onSelectChange(data) {
                // 如果长度为0说明当前没有任何节点被选中
                if (data.length == 0) {
                    this.orgParentId = '0';
                    this.orgParentName = '顶层节点';
                    this.hasChildren = false;
                } else {
                    this.orgParentId = data[0].orgId;
                    this.orgParentName = data[0].title;
                    if (data[0].children.length == 0) {
                        this.hasChildren = false;
                    } else {
                        this.hasChildren = true;
                    }
                }
            },
            initOrgTree() {
                const _this = this;
                getAllOrgList({}).then(res => {
                    _this.orgTreeDate = res.entity;
                });
            }
        },
        mounted() {
            // 初始化完成加载组织架构节点数据
            this.initOrgTree();
            // 初始化完成加载用户节点数据
            this.handleSearch();
        },
        watch:{
            orgParentName(){
                this.selection = [];
                this.handleSearch();
            }
        }
    };
</script>
<style lang="less">
    @import './index.less';
</style>